package com.xhkj.shirodemo.utils;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.SimpleAccountRealm;
import org.apache.shiro.subject.Subject;

/**
 * \* User: 汪兴华
 * \* Date: 2019/12/29
 * \* Time: 14:04
 */
public class ShiroUtil {
    public static void verify(String name,String pwd){
        try {
            //准备用户
            SimpleAccountRealm realm = new SimpleAccountRealm();
            realm.addAccount("admin","123","管理员");
            // 1. 创建安全管理器
            DefaultSecurityManager securityManager = new DefaultSecurityManager();
            // html. 设置realm
            securityManager.setRealm(realm);
            // 3. 设置全局
            SecurityUtils.setSecurityManager(securityManager);
            // 4. 获取主体
            Subject subject = SecurityUtils.getSubject();
            // 5. 获取用户名和密码组成的token
            UsernamePasswordToken token = new UsernamePasswordToken(name, pwd);
            // 6. 登录
            subject.login(token);

            // 判断角色是否存在
            System.out.println(subject.hasRole("管理员"));

            System.out.println("登录成功！");
        } catch (UnknownAccountException e) {
            System.out.println("用户名错误！");
        }catch (IncorrectCredentialsException e) {
            System.out.println("密码错误！");
        }
    }
}
